//
//  ChatViewModel.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/2/7.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit
import HandyJSON
import Moya

//struct ChatModel: HandyJSON {
//    var doctorName: String?
//    /// 诊断状态: 0-未诊断 1-诊断中 2-已结束
//    var flag: Int = 0
//    /// 诊断id
//    var diagnoseId: Int = 0
//    /// 医生的用户id
//    var doctorUserId: Int = 0
//    /// 未读信息数
//    var unreadCount: Int = 0
//    /// 第一条未读信息的id
//    var msgId: String?
//    /// 医生职称
//    var jobTitle: String?
//
//    var imMessage: [ChatMsgModel]?
//}

class ChatViewModel: NSObject {
    var msgModels: [ChatMsgModel]
    
    init(msgModels: [ChatMsgModel]) {
        self.msgModels = msgModels
    }
    
    var numberOfRows: Int {
        return msgModels.count
    }
    
    func viewModel(fro indexPath: IndexPath) -> ChatMsgViewModel {
        return ChatMsgViewModel(model: msgModels[indexPath.row])
    }
    
    func insert(msgModel: ChatMsgModel, isBottom: Bool = true) {
        isBottom ? msgModels.append(msgModel) : msgModels.insert(msgModel, at: 0)
        if isBottom {
            updatePlayingIndex(count: 1)
        }   
    }
    
    func removeFirst() -> ChatMsgModel {
        return msgModels.remove(at: 0)
    }
    
    func insert(models: [ChatMsgModel], isBottom: Bool = true) {
        if isBottom {
            msgModels += models
            updatePlayingIndex(count: models.count)
        } else {
            msgModels = models + msgModels
        }
    }
    
    func updatePlayingIndex(count: Int) {
        if playingIndexPath != nil, let playing = RecordManager.sharedInstance.player?.isPlaying, playing{
            playingIndexPath! += count
        }
    }
    
    var playingIndexPath: Int?
}

extension ChatViewModel {
    static func getChatRecord(diagnoseId: String,
                              current: Int,
                              success: @escaping (_ models: [ChatMsgModel]) -> Void,
                              failure: @escaping (_ errorMsg: String?) -> Void)
    {
        let paras: [String: Any] = [
            "diagnoseId": diagnoseId,
            "current": current,
            "size": 10
        ]
        HttpTool.shared.request(target: ApiManager.chatRecord(paras: paras), success: { (json, code) in
            switch code {
            case .failure:
                failure(json["message"].description)
            case .success:
                if let models = JSONDeserializer<ChatMsgModel>.deserializeModelArrayFrom(json: json["data"]["records"].description) as? [ChatMsgModel] {
                    success(models)
                } else {
                    failure("请求数据发生错误，稍候重试!")
                }
            }
        }) { errorMsg in
            failure(errorMsg)
        }
    }
    
    /// 上传IM图片
    // bucket: 图片桶类型 默认 9
    // type: 图片类型  默认 92
    // relationId: 病例id 默认 1
    // checkStatus: 图片审核状态 默认 .none
    static func uploadImage(image: UIImage,
                            bucket: Int = 9,
                            type: Int = 92,
                            relationId: Int = 1,
                            checkStatus: UploadImageStatus = .none,
                            success: @escaping (_ model: UploadImgModel) -> Void,
                            failure: @escaping (_ errorMsg: String?) -> Void)
    {
        var formDatas = [MultipartFormData]()
        let imageData = image.jpegData(compressionQuality: 1) ?? Data()
        let fileName = "\(Date.milliseconds).jpg"
        
        let formData = MultipartFormData(provider: .data(imageData), name: "file", fileName: fileName, mimeType: "image/jpeg")
        formDatas.append(formData)
        
        let paras: [String: Any] = ["bucket": bucket,
                                    "type": type,
                                    "relationId": relationId,
                                    "checkStatus": checkStatus.rawValue]
        HttpTool.shared.request(target: ApiManager.uploadImage(formDatas, paras: paras), success: { (json, code) in
            switch code {
            case .failure:
                failure(json["message"].description)
            case .success:
                if let model = JSONDeserializer<UploadImgModel>.deserializeFrom(json: json["data"].description) {
                    success(model)
                } else {
                    failure("请求数据发生错误，稍候重试")
                }
            }
        }) { errorMsg in
            failure(errorMsg)
        }
    }
    
    /// 上传IM音频
   static func uploadIMAudio(filePath: String,
                             bucket: Int = 9,
                             type: Int = 93,
                             time: Int = 0,
                             success: @escaping (_ model: UploadAudioModel) -> Void,
                             failure: @escaping (_ errorMsg: String?) -> Void) {
       
       guard let audioData = try? Data.init(contentsOf: URL(fileURLWithPath: filePath)) else { return }
       var formDatas = [MultipartFormData]()
       let fileName = "\(Date.milliseconds).mp3"
       let formData = MultipartFormData(provider: .data(audioData), name: "file", fileName: fileName, mimeType: "audio/mpeg")
       formDatas.append(formData)
       let paras = ["bucket" : bucket,
                    "type" : type,
                    "time" : time]
       HttpTool.shared.request(target: ApiManager.uploadIMAudio(formDatas, paras: paras), success: { (json, code) in
           switch code {
           case .failure:
               failure(json["message"].description)
           case .success:
               if let model = JSONDeserializer<UploadAudioModel>.deserializeFrom(json: json["data"].description) {
                   success(model)
               } else {
                   failure("请求数据发生错误，稍候重试")
               }
           }
       }) { (errorMsg) in
           failure(errorMsg)
       }
   }
    
    /// 查询处方消息
    static func queryPrescriptionMsg(prescriptionId: String,
                                     success: @escaping (_ model: PrescriptionDetailModel) -> Void,
                                     failure: @escaping (_ errorMsg: String?) -> Void) {
        let paras = ["id": prescriptionId]
        YSGLog("处方详情 paras: \(paras)")
        HttpTool.shared.request(target: ApiManager.queryPrescription(paras: paras), success: { (json, code) in
            YSGLog("处方详情 json: \(json)")
            switch code {
            case .failure:
                failure(json["message"].description)
            case .success:
                if let model = PrescriptionDetailModel.deserialize(from: json["data"].description) {
                    success(model)
                } else {
                    failure("请求数据发生错误，稍后重试")
                }
            }
        }) { errorMsg in
            failure(errorMsg)
        }
    }
}
